package com.clw.classfile.attribute.info;

import com.clw.classfile.BytesReader;

/**
 * Created by chengliwei on 2018/11/16.
 */
public class LocalVariableTable extends AttributeInfo {

    // 描述栈帧局部变量表中的变量与Java源码中定义的变量之间的关系，可选，可以通过javac -g:none或-g:vars关闭或生成这项信息
    private short localVariableTableLength;
    private LocalVariableInfo[] localVariableInfo;

    private class LocalVariableInfo {

        private short startPc; // 局部变量生命周期开始的字节码偏移量
        private short length; // 作用范围覆盖的长度
        private short nameIndex; // 指向常量池CONSATNT_Utf8_info型的引用，局部变量的名称
        private short descriptorIndex; // 指向常量池CONSATNT_Utf8_info型的引用，局部变量的描述符
        private short index; // 这个局部变量在栈帧局部变量表中Slot的位置。当变量类型是double或float（64位），占用的Slot位index和index+1两个

        public LocalVariableInfo(short startPc, short length, short nameIndex,
                short descriptorIndex,
                short index) {
            this.startPc = startPc;
            this.length = length;
            this.nameIndex = nameIndex;
            this.descriptorIndex = descriptorIndex;
            this.index = index;
        }
    }

    public LocalVariableTable(BytesReader reader) {
        super(reader.readInt());
        this.localVariableTableLength = reader.readShort();
        this.localVariableInfo = new LocalVariableInfo[localVariableTableLength];
        for (int i = 0; i < localVariableTableLength; i++) {
            localVariableInfo[i] = new LocalVariableInfo(reader.readShort(), reader.readShort(),
                    reader.readShort(), reader.readShort(), reader.readShort());
        }
    }
}
